package com.youth.oauth.config.security;

import cn.hutool.json.JSONUtil;
import com.youth.oauth.commons.beans.Result;
import com.youth.oauth.config.redis.RedisClient;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义注销成功处理类
 * 实现了LogoutSuccessHandler接口，用于在用户成功注销后进行自定义处理
 */
@Component
public class LogoutStatusSucessHandler implements LogoutSuccessHandler {

    @Resource
    RedisClient redisClient;

    /**
     * 注销成功后的处理方法
     *
     * @param request        HttpServletRequest对象，包含本次请求的相关信息
     * @param response       HttpServletResponse对象，用于向客户端发送响应
     * @param authentication Authentication对象，代表当前用户的身份信息
     * @throws IOException 如果在处理过程中发生I/O错误
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        String token = request.getHeader("token");
        if (StringUtils.hasText(token)) {
            String key = "login:token:" + token;
            System.out.println(key);
            redisClient.del(key);
        }
        // 设置响应的字符编码和内容类型
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");

        // 创建一个表示注销成功的Result对象
        Result result = Result.ok("注销成功");

        // 将Result对象转换为JSON字符串
        String jsonStr = JSONUtil.toJsonStr(result);

        // 通过response对象将JSON字符串写入响应体中
        response.getWriter().write(jsonStr);
    }
}
